package com.example.camerademo;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import java.io.File;
import java.util.List;

/**
 * author: wj
 * created on: 2021/4/1 14:40
 * description: 选择图片并显示到当前界面
 */
public class ImageGalleryDemoActivity extends Activity {

    private static final int PHOTO_REQUEST_CAMERA = 1;  // 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;  // 图库重选择
    private static final int PHOTO_REQUEST_CUT = 3;  // 结果

    private ImageView imageView;

     /* 图片名称 */
     private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
     private File tempFile;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_gallery_demo);
        imageView = findViewById(R.id.imageView);
    }

    /**
     * 从图库获取
     * @param view
     */
    public void gallery(View view) {
        // 激活系统图库，选择一张图片
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_GALLERY
        startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
    }

    /**
     * 从相机获取
     * @param view
     */
    public void camera(View view) {
        // 判断是否有相机
        boolean b = hasCamera(ImageGalleryDemoActivity.this);
        if (!b) {
            Toast.makeText(ImageGalleryDemoActivity.this, "系统无相机", Toast.LENGTH_SHORT).show();
        } else {
            // 激活相机
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            // 判断存储卡是否可用，可用进行存储
            if (hasSdcard()) {
                tempFile = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME);
                // 从文件中创建uri
                Uri uri = Uri.fromFile(tempFile);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            }
            // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CAMERA
            startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
        }
    }

    /**
     * 判断系统中是否存在可以启动的相机应用
     *
     * @return 存在返回true，不存在返回false
     */
    @SuppressLint("QueryPermissionsNeeded")
    public static boolean hasCamera(Context context) {
        // 虚拟机没有摄像头，模拟器有一个摄像头
        PackageManager packageManager = context.getPackageManager();
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        return list.size() > 0;
    }

    /**
     * 剪切图片
     * @param uri
     */
    private void crop(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true"); // 开启剪切

        // 裁剪框的比例 宽高比 1 : 1
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        // 裁剪后输出图片的尺寸大小
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);

        intent.putExtra("outputFormat", "JPEG");// 图片格式
        intent.putExtra("noFaceDetection", true);// 取消人脸识别
        intent.putExtra("return-data", true);
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CUT
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

    /**
     * 判断SDK是否被挂载
     * @return
     */
    private boolean hasSdcard() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    @SuppressLint("WrongConstant")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PHOTO_REQUEST_GALLERY) {
            // 从相册返回数据
            if (data != null) {
                // 得到图片的全路径
                Uri uri = data.getData();
//                System.out.println(uri);
                crop(uri);
            }
        } else if (requestCode == PHOTO_REQUEST_CAMERA) {
            // 从相机返回数据
            if (hasSdcard()) {
//                System.out.println(data.getData());
//                System.out.println(Uri.fromFile(tempFile));
                crop(Uri.fromFile(tempFile));
            } else {
                Toast.makeText(ImageGalleryDemoActivity.this, "未找到储存卡，无法存储图片！", 0).show();
            }
        } else if (requestCode == PHOTO_REQUEST_CUT) {
            // 从剪切图片返回的数据
            if (data != null) {
                Bitmap bitmap = data.getParcelableExtra("data");
                imageView.setImageBitmap(bitmap);
            }
            try {
                // 删除临时文件
                if (tempFile != null) {
                    Boolean b = tempFile.delete();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
